﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kaio.Web.UI;
using MvcForum.Net.Bussiness;
using SortDirection = MvcForum.Net.Bussiness.SortDirection;

namespace MvcForum.Net.Controllers
{
    [ValidateAuthentication(AdminRequired = true)]
    public class AdminController : Controller
    {

       /* public List<ForumUrl> Address
        {
            get
            {

                return new List<ForumUrl>
                           {
                               new ForumUrl
                                   {
                                       Title = ForumContext.GetText(LanguageSection.ADMIN,"PAGE_NAME"),
                                       Url = ForumContext.GetAbsoluteUrl(ForumUrls.ADMIN)
                                   }
                           };
            }
        }*/

        //
        // GET: /Admin/
        
        public ActionResult Index()
        {
            return View();
        }

        #region Forum Manager

        public ActionResult Forum()
        {

            System.Threading.Thread.Sleep(2000);

            int id;

            int.TryParse(Request.QueryString["Id"], out id);

            var _url = new ForumUrl
                           {
                               Title = ForumContext.GetText(LanguageSection.FORUM_MANAGER, "PAGE_NAME"),
                               Url = ForumContext.GetAbsoluteUrl(ForumUrls.ADMIN_FORUM_MANAGER)
                           };
            

            Forum _f = id > 0 ? ForumRepo.Detail(id) : null;


            #region Forum List

            var _forums = ForumRepo.ListAll();

            var _parentList = new List<SelectListItem>
                                  {
                                      new SelectListItem
                                          {
                                              Text = ForumContext.GetText(LanguageSection.FORUM_MANAGER, "ROOT"),
                                              Value = "0"
                                          }
                                  };
            _parentList.AddRange(from f in _forums
                                 where _f == null || _f.ForumId != f.ForumId
                                 select new SelectListItem
                                            {
                                                Text = string.Format("{0}{1}", ForumContext.Padding(f.Level), f.ForumName),
                                                Value = f.ForumId.ToString(),
                                                Selected = _f != null && _f.ForumId == f.ParentId
                                            });

            #endregion

            #region Roles

            var _roles = RoleRepo.List();

            var _allowRoles = _roles.Select(role => new SelectItem
                                                        {
                                                            Text = role.RoleName,
                                                            Value = role.RoleId.ToString()
                                                        }).ToList();

            ViewBag.AllowRoles = _allowRoles;// new MultiSelectList(_roles.AsEnumerable(), "RoleId", "RoleName", _oldAllowRoles.AsEnumerable());

            #endregion


            #region ModerateType

            var _modTypes = Enum.GetValues(typeof(ModerateType));

            ViewBag.ModerateTypes = (from int val in _modTypes
                                     select new SelectItem
                                                {
                                                    Text = ForumContext.GetText(LanguageSection.FORUM_MANAGER, "MODERATE_" + Enum.GetName(typeof(ModerateType), val)),
                                                    Value = val.ToString(),
                                                    Selected = _f != null && _f.ModerateType == val
                                                }).ToList();


            //new SelectList(_moderateTypes, "Value", "Text", _f != null?_f.ModerateType:(int)ModerateType.None);



            #endregion


            #region YesNo


            ViewBag.YesNo = new List<SelectItem>()
                                {
                                    new SelectItem
                                        {
                                            Text = "Yes",
                                            Value = "true",
                                            CssClass = "radio-yes"
                                        },
                                    new SelectItem
                                        {
                                            Text = "No",
                                            Value = "false",
                                            CssClass = "radio-no"
                                        }
                                };

            #endregion

            #region Default Sort options

            var _sortByValues = Enum.GetValues(typeof(SortOrderBy));

            ViewBag.SortOrderBy = (from int value in _sortByValues
                                   select new SelectItem
                                              {
                                                  Text = ForumContext.GetText(LanguageSection.FORUM_MANAGER, "ORDER_BY_" + Enum.GetName(typeof(SortOrderBy), value)),
                                                  Value = value.ToString(),
                                                  Selected = _f != null && _f.OrderBy == value
                                              }).ToList();


            ViewBag.SortDir = new List<SelectListItem>
                                        {
                                             new SelectListItem
                                                {
                                                    Text = ForumContext.GetText(LanguageSection.FORUM_MANAGER, "DESC"),
                                                    Value = ((int) SortDirection.DESC).ToString(),
                                                    Selected = _f == null || _f.SortDirection == (int) SortDirection.DESC
                                                },
                                            new SelectListItem
                                                {
                                                    Text = ForumContext.GetText(LanguageSection.FORUM_MANAGER, "ASC"),
                                                    Value = ((int) SortDirection.ASC).ToString(),
                                                    Selected = _f != null && _f.SortDirection == (int) SortDirection.ASC
                                                }

                                               
                                        };

            #endregion

            ViewBag.ActiveUrl = _url;
           
            ViewBag.ParentList = _parentList;

            ViewBag.ForumList = _forums;

            ViewBag.ButtonText = ForumContext.GetText(LanguageSection.GLOBAL, _f != null ? "UPDATE" : "SAVE");
            

            return View(_f);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Forum(FormCollection form)
        {

            var _msg = Msg.Create();

            var _act = Request["act"];
            switch (_act)
            {
                case "del":

                    ForumRepo.Del(form["Ids"]);
                    _msg.Reload = true;
                    break;

                default:
                    var _f = new Forum();
                    TryUpdateModel(_f, form.ToValueProvider());
                    _f.AllowRoles = form["AllowRoles"];

                    ForumRepo.Save(_f);
                    _msg.ReturnUrl = form["ReturnUrl"];
                    _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, _f.ForumId > 0 ? "UPDATE_SUCCESS" : "INSERT_SUCCESS");
                    break;
            }

            //_msg.ReturnUrl = form["returnUrl"];

            return JavaScript(_msg.ToJavaScript());
        }


        #endregion



        #region Role Manager

        public ActionResult Role()
        {


            var _url = new ForumUrl
                           {
                               Title = ForumContext.GetText(LanguageSection.ROLE_MANAGER, "PAGE_NAME"),
                               Url = ForumContext.GetAbsoluteUrl(ForumUrls.ADMIN_ROLE_MANAGER)
                           };

            ViewBag.ActiveUrl = _url;


            int id;

            int.TryParse(Request.QueryString["Id"], out id);

            Role _o = id > 0 ? RoleRepo.Info(id) : null;



            #region YesNo


            ViewBag.YesNo = new List<SelectItem>
                                {
                                    new SelectItem
                                        {
                                            Text = "Yes",
                                            Value = "true",
                                            CssClass = "radio-yes"
                                        },
                                    new SelectItem
                                        {
                                            Text = "No",
                                            Value = "false",
                                            CssClass = "radio-no"
                                        }
                                };

            #endregion


            ViewBag.List = RoleRepo.List();

            ViewBag.ButtonText = ForumContext.GetText(LanguageSection.GLOBAL, _o != null ? "UPDATE" : "SAVE");

            return View(_o);


        }


        [HttpPost]
        public ActionResult Role(FormCollection form)
        {


            var _msg = Msg.Create();

            if (form["act"] == "del")
            {

                RoleRepo.Del(form["Ids"]);

                _msg.Reload = true;
            }
            else
            {

                var r = new Role();

                TryUpdateModel(r, form.ToValueProvider());

                //if (!bool.Parse(form["IsAdmin"]) && !bool.Parse(form["IsSuperModerator"]))

                var excludeKeys = new string[] { "RoleName", "IsAdmin", "RoleId", "IsSuperModerator", "AllowLogin", "IsAutoStart", "CssClass","ReturnUrl", "fvalid", "ajax" };


                var _sb = new StringBuilder();

                foreach (string k in form.Keys)
                {
                    if (!excludeKeys.Any(x => x.ToLower() == k.ToLower()))
                    {
                        _sb.AppendFormat("{0}{1}:{2}", _sb.Length > 0 ? "|" : string.Empty, k, form[k]);
                    }
                }

                r.AccessMask = _sb.ToString();

                RoleRepo.Save(r);

                _msg.ReturnUrl = form["ReturnUrl"];
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, r.RoleId > 0 ? "UPDATE_SUCCESS" : "INSERT_SUCCESS");
            }


            //Reset Session and permissions

            Session.RemoveAll();
            Session.Clear(); 
            return JavaScript(_msg.ToJavaScript());
        }


        #endregion



        #region Moderator

        public ActionResult Moderator()
        {
            int id;

            int.TryParse(Request.QueryString["Id"], out id);

            var _url = new ForumUrl
                           {
                               Title = ForumContext.GetText(LanguageSection.MODERATOR_MANAGER, "PAGE_NAME"),
                               Url = ForumContext.GetAbsoluteUrl(ForumUrls.ADMIN_MODERATOR_MANAGER)

                           };

            ViewBag.ActiveUrl = _url;

            var _o = id > 0 ? ModerateRepo.Info(id) : null;

            #region YesNo


            ViewBag.YesNo = new List<SelectItem>
                                {
                                    new SelectItem
                                        {
                                            Text = "Yes",
                                            Value = "true",
                                            CssClass = "radio-yes"
                                        },
                                    new SelectItem
                                        {
                                            Text = "No",
                                            Value = "false",
                                            CssClass = "radio-no"
                                        }
                                };

            #endregion


            #region Moderate Email Type



          /*  var _modTypes = Enum.GetValues(typeof(ModerateEmailType));

            ViewBag.ModerateEmailTypes = (from int val in _modTypes
                                     select new SelectItem
                                     {
                                         Text = ForumContext.GetText(LanguageSection.MODERATOR_MANAGER, "MODERATE_EMAIL_" + Enum.GetName(typeof(ModerateEmailType), val)),
                                         Value = val.ToString(),
                                         Selected = _o != null && _o.ModerateEmailType == val
                                     }).ToList();*/


            #endregion


            #region Forum List

            var _forums = ForumRepo.ListAll();

            ViewBag.ForumLists = _forums.Select(f => new SelectItem
                                                      {
                                                          Text = string.Format("{0}{1}", ForumContext.Padding(f.Level), f.ForumName),
                                                          Value = f.ForumId.ToString(),
                                                          CssClass = f.ParentId == 0 ? "bold" : string.Empty
                                                      }).ToList();


            #endregion


            

            ViewBag.ButtonText = ForumContext.GetText(LanguageSection.GLOBAL, _o != null ? "UPDATE" : "SAVE");


            ViewBag.List = ModerateRepo.List();

            return View(_o);

        }

        [HttpPost]
        public ActionResult Moderator(FormCollection form)
        {
            var _msg = Msg.Create();


            if (form["act"] == "del")
            {

                var _ids = form["ids"];

                if (!string.IsNullOrWhiteSpace(_ids))
                {
                    ModerateRepo.Del(_ids);
                    _msg.Reload = true;
                }
                else
                {
                    _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "MUST_SELECT_ITEM");
                }

                return Json(_msg);


            }


            int id;

            int.TryParse(form["Id"], out id);


            var _forums = form["forums"];

            if (string.IsNullOrWhiteSpace(_forums))
            {
                _msg.Text = ForumContext.GetText(LanguageSection.MODERATOR_MANAGER, "MUST_SELECT_ONE_ITEM");

                return Json(_msg);
            }

            var _username = form["username"];

            var _u = UsersRepo.UserInfo(_username);

            if (_u!=null)
            {


               
                var excludeKeys = new string[] { "Id", "UserName", "ModerateEmailType", "Forums", "returnUrl" };

                var _sb = new StringBuilder();

                foreach (string k in form.Keys)
                {
                    if (!excludeKeys.Any(x => x.ToLower() == k.ToLower()))
                    {
                        _sb.AppendFormat("{0}{1}:{2}", _sb.Length > 0 ? "|" : string.Empty, k, form[k]);
                    }
                }


                var _fs = _forums.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string f in _fs)
                {
                    var fid = int.Parse(f);

                    ModerateRepo.Save(_u.UserId, _u.UserName, fid, _sb.ToString());
                }

                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, id > 0 ? "UPDATE_SUCCESS" : "INSERT_SUCCESS");

            }
            else
            {
                _msg.Text = string.Format(ForumContext.GetText(LanguageSection.MESSAGES, "USERNOTEXISTS"), _username);
            }

            _msg.ReturnUrl = form["returnUrl"];

            return JavaScript(_msg.ToJavaScript());

        }

        #endregion


        #region IPLOCK


        public ActionResult IPLock()
        {

            int id;

            int.TryParse(Request.QueryString["Id"], out id);

            var _url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.IPLOCKS, "PAGE_NAME"),
                Url = ForumContext.GetAbsoluteUrl(ForumUrls.ADMIN_IPLOCKS_MANAGER)

            };

            ViewBag.ActiveUrl = _url;

            var _o = id > 0 ? IPLockRepo.Info(id) : null;

            if(_o!=null)
            {
                _o.Expires = _o.Expires.ToUserTimeZoneDateTime();
            }

            ViewBag.ButtonText = ForumContext.GetText(LanguageSection.GLOBAL, _o != null ? "UPDATE" : "SAVE");

            ViewBag.List = IPLockRepo.All();

            return View(_o);

        }

        [HttpPost]
        public ActionResult IPLock(FormCollection form)
        {
            var _msg = Msg.Create();

            if (form["act"]=="del")
            {
                var _ids = form["ids"];

                if (!string.IsNullOrWhiteSpace(_ids))
                {
                    IPLockRepo.Del(_ids);
                    _msg.Reload = true;
                }
                else
                {
                    _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "MUST_SELECT_ITEM");
                }
            }
            else
            {
                var _o = new IPLock();

                TryUpdateModel(_o, form.ToValueProvider());

                _o.Expires = _o.Expires.ToUtcDateTime();

                IPLockRepo.Save(_o);

                _msg.ReturnUrl = form["returnUrl"];
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, _o.Id > 0 ? "UPDATE_SUCCESS" : "INSERT_SUCCESS");     
            }
            
            

            return JavaScript(_msg.ToJavaScript());

        }


        #endregion
    }
}
